﻿using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using MvvmHelpers;
using System.Collections.Generic;
using System.Threading.Tasks;
using TabbedTemplate.Converters;
using TabbedTemplate.Models;
using TabbedTemplate.Services;

namespace TabbedTemplate.ViewModels
{
    public class StorePunchesViewModel : ViewModelBase
    {
        /// <summary>
        /// 收藏。
        /// </summary>
        public Favorite Favorite
        {
            get => _favorite;
            set => Set(nameof(Favorite), ref _favorite, value);
        }

        /// <summary>
        /// 收藏。
        /// </summary>
        private Favorite _favorite;

        /// <summary>
        /// 正在载入。
        /// </summary>
        public bool Loading
        {
            get => _loading;
            set => Set(nameof(Loading), ref _loading, value);
        }

        private PunchTimeStampParameter _punchTimeStampParameter;

        public PunchTimeStampParameter EditPunchMessageParameter
        {
            get => _punchTimeStampParameter;
            set =>
                Set(nameof(EditPunchMessageParameter),
                    ref _punchTimeStampParameter, value);
        }

        private bool _loading;

        /// <summary>
        /// 店铺。
        /// </summary>
        public Store Store
        {
            get => _store;
            set => Set(nameof(Store), ref _store, value);
        }

        /// <summary>
        /// 店铺。
        /// </summary>
        private Store _store;


        // ******** 公开属性
        public ObservableRangeCollection<PunchTimeStampParameter>
            _punchHistoryCollection;

        public ObservableRangeCollection<PunchTimeStampParameter>
            PunchHistoryCollection
        {
            get => _punchHistoryCollection;
            set =>
                Set(nameof(PunchHistoryCollection), ref _punchHistoryCollection,
                    value);
        }

        private IPunchNavigationService _punchNavigationService;
        private IFavoriteStorage _favoriteStorage;

        private IStoreStorage _storeStorage;

        private IPunchInfoStorage _punchInfoStorage;
        private IPreferenceStorage _preferenceStorage;

        public StorePunchesViewModel(
            IPunchNavigationService punchNavigationService,
            IFavoriteStorage favoriteStorage, IStoreStorage storeStorage,
            IPunchInfoStorage punchInfoStorage, IPreferenceStorage preferenceStorage)
        {
            _punchNavigationService = punchNavigationService;
            _favoriteStorage = favoriteStorage;
            _storeStorage = storeStorage;
            _punchInfoStorage = punchInfoStorage;
            _preferenceStorage = preferenceStorage;
            _punchHistoryCollection =
                new ObservableRangeCollection<PunchTimeStampParameter>();


        }


        /// <summary>
        /// 页面初始化命令。
        /// </summary>
        private RelayCommand _pageAppearingCommand;

        public RelayCommand PageAppearingCommand =>
            _pageAppearingCommand ??= new RelayCommand(async () => await PageAppearingCommandFunction());

        public async Task PageAppearingCommandFunction()
        {
            //管理偏好存储
            _preferenceStorage.Set("newQuery", false);
            _punchHistoryCollection.Clear();
            if (!_favoriteStorage.Initialized())
            {
                await _favoriteStorage.InitializeAsync();
            }

            if (!_punchInfoStorage.PunchInfoStorageInitialized())
            {
                await _punchInfoStorage.PunchInfoStorageInitializeAsync();
            }

            var tempCollection = (List<PunchInfo>)
                await _punchInfoStorage.GetAllPunchInfoByStoreUid(Store.Uid);
            tempCollection.Sort((b1, b2) =>
                Comparer<long>.Default.Compare(b2.Timestamp, b1.Timestamp));

            foreach (var p in tempCollection)
            {
                var param = new PunchTimeStampParameter
                {
                    DateTime =
                        ConvertTimeStamp.ConvertTimeStampToDate(p.Timestamp),
                    PunchInfo = p
                };

                PunchHistoryCollection.Add(param);
            }

            Loading = true;
            var favorite = await _favoriteStorage.GetFavoriteAsync(Store.Uid) ??
                new Favorite { StoreUid = Store.Uid };
            isFavorite = favorite.IsFavorite;
            Favorite = favorite;
            Loading = false;
        }

        /// <summary>
        /// 打卡记录点击命令(历史。)
        /// </summary>
        private RelayCommand<PunchTimeStampParameter>
            _punchMessageTappedCommand;

        public RelayCommand<PunchTimeStampParameter>
            PunchMessageTappedCommand =>
            _punchMessageTappedCommand ??=
                new RelayCommand<PunchTimeStampParameter>(
                    async punchTimeStampParameter =>
                        await PunchMessageTappedCommandFunction(
                            punchTimeStampParameter));

        public async Task PunchMessageTappedCommandFunction(

            PunchTimeStampParameter punchTimeStampParameter)
        {
            _preferenceStorage.Set("PunchEdit", true);
            punchTimeStampParameter.Store = this.Store;
            await _punchNavigationService.NavigateToPunchViewPage(
                punchTimeStampParameter);
        }


        /// <summary>
        /// 打卡点击命令
        /// </summary>
        private RelayCommand _punchTappedCommand;

        public RelayCommand PunchTappedCommand =>
            _punchTappedCommand ??= new RelayCommand(async () =>
                await PunchTappedCommandFunction());

        public async Task PunchTappedCommandFunction()
        {
            _preferenceStorage.Set("newPunch", true);
            PunchTimeStampParameter e = new PunchTimeStampParameter()
            {
                PunchInfo = new PunchInfo
                {
                    Content = "",
                    Store_Uid = Store.Uid
                },
                Store = Store
            };
            await _punchNavigationService.NavigateToPunchPage(e);
        }

        /// <summary>
        /// 收藏切换命令。
        /// </summary>
        public RelayCommand FavoriteToggledCommand =>
            _favoriteToggledCommand ??= new RelayCommand(async () =>
                await FavoriteToggledCommandFunction());

        /// <summary>
        /// 收藏切换命令。
        /// </summary>
        private RelayCommand _favoriteToggledCommand;

        public async Task FavoriteToggledCommandFunction()
        {
            if (isFavorite == Favorite.IsFavorite)
                return;
            isFavorite = Favorite.IsFavorite;

            if (!_storeStorage.UserCacheInitialized())
            {
                await _storeStorage.UserCacheInitializeAsync();
            }

            Loading = true;
            await _favoriteStorage.SaveFavoriteAsync(Favorite, true);
            await _storeStorage.InsertAStore(Store);
            Loading = false;
        }



        public RelayCommand<object> DeleteHistoryCommand =>
            _deleteHistoryCommand ??= new RelayCommand<object>(async (param) =>
                await DeleteHistoryCommandFunction(param));

        private RelayCommand<object> _deleteHistoryCommand;

        public async Task DeleteHistoryCommandFunction(object o)
        {
            var a = (PunchTimeStampParameter)o;
            PunchHistoryCollection.Remove(a);
            //TODO 删除处存在问题。
            await _punchInfoStorage.DeletePunchInfoByIdAsync(a.PunchInfo);
        }
        /******** 私有变量 ********/

        /// <summary>
        /// 是否为收藏。
        /// </summary>
        public bool isFavorite;
    }
}
